package com.hustcs.mindmap.database;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

import com.hustcs.mindmap.drawmap.Node;

public class ReadFromFile {
	private String filepath;
	private FileInputStream inputStream;
    private ObjectInputStream objectInputStream;
    
    private ArrayList<Node> preorder;
    private ArrayList<Node> inorder;
    
    private int nodeNum;
    
    public ReadFromFile(String filepath) {
    	this.filepath = filepath;    	
    }    
	
	public boolean initInputStream() throws IOException {
		inputStream = new FileInputStream(filepath);
		objectInputStream = new ObjectInputStream(inputStream);
		if (objectInputStream == null) {
			return false;
		}
		return true;
	}
	
	public NodeTree buildFromFile() throws IOException, ClassNotFoundException {
		Node node;
		for (int i = 0; i < nodeNum; i++) {
			node = (Node)objectInputStream.readObject();
			preorder.add(node);
		}
		for (int i = 0; i < nodeNum; i++) {
			node = (Node)objectInputStream.readObject();
			inorder.add(node);
		}
		
		return buildTree(0, 0, nodeNum-1);
	}
	public NodeTree buildTree(int i, int lo, int hi) {
		if (i >= preorder.size() || lo > hi) {
			return null;
		}
		
		NodeTree nodeTree = new NodeTree();
		nodeTree.makeRoot(preorder.get(i));
		
		int j;
		for (j = lo; j <= hi; j++) {
			if (preorder.get(i).equals(inorder.get(j))) {
				break;
			}
		}
		
		NodeTree leftSub = buildTree(i+1, lo, j-1);
		NodeTree rightSub = buildTree(i+j-lo+1, j+1, hi);
		nodeTree.attachLeft(leftSub);
		nodeTree.attachRigth(rightSub);
		
		return nodeTree; 
	}
	
	public void close() throws IOException {
		inputStream.close();
		objectInputStream.close();
	}
}
